<template>
  <div class="app-container">
    <div class="cardBox">
      <el-form :inline="true" class="search-form">
        <el-row style="display: flex; flex-wrap: wrap">
          <div style="flex: 1">
            <el-form-item label="模版名称：">
              <el-input
                placeholder="请输入模版名称"
                v-model="searchForm.template_name"
                maxlength="20"
                show-word-limit
                onkeyup="value =value.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="类型：">
              <el-select v-model="searchForm.type" placeholder="请选择类型">
                <el-option
                  v-for="item in [
                    { name: '积分', id: 1 },
                    { name: '提货券', id: 2 },
                    { name: '提货券比例范围', id: 3 },
                    { name: '未中奖', id: 99 },
                  ]"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态：">
              <el-select v-model="searchForm.status" placeholder="请选择状态">
                <el-option
                  v-for="item in [
                    { name: '已启用', id: 1 },
                    { name: '已关闭', id: 2 },
                  ]"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item>
              <el-button
                size="small"
                type="primary"
                icon="el-icon-search"
                @click="getListWay"
                >查询</el-button
              >
              <el-button
                size="small"
                type="primary"
                icon="el-icon-refresh"
                @click="resetting"
                >重置</el-button
              >
            </el-form-item>
          </div>
        </el-row>
      </el-form>
    </div>
    <div class="cardBox" style="margin-top: 20px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-button
            v-hasPermi="'raffle/save'"
            icon="el-icon-plus"
            size="small"
            type="primary"
            @click="saveWay()"
            >添加模版</el-button
          >
        </el-col>
        <el-col :span="8" style="float: right">
          <div class="right-panel el-button-group">
            <el-button
              class=""
              icon="el-icon-refresh"
              size="mini"
              @click="resetting"
            ></el-button>
            <el-dropdown trigger="click" :hide-on-click="false">
              <span class="el-dropdown-link">
                <el-button
                  class=""
                  icon="el-icon-s-operation"
                  size="mini"
                ></el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="fruit in allTableThead" :key="fruit">
                  <el-checkbox v-model="checkboxTableThead" :label="fruit">{{
                    tableTheadOptions[fruit].label
                  }}</el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
      <el-col class="marginTop">
        <el-table
          v-loading="loading"
          highlight-current-row
          :data="dataList"
          :header-cell-style="{
            'background-color': '#f3f8fe',
            color: '#606266',
            height: '50px',
          }"
          style="width: 100%"
        >
          <el-table-column
            v-for="fruit in tableThead"
            :key="fruit"
            :label="tableTheadOptions[fruit].label"
            min-width="80"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="fruit == 'status'">
                <el-tag v-if="scope.row.status == 1" type="success"
                  >已启用</el-tag
                >
                <el-tag v-if="scope.row.status == 2" type="warning"
                  >已禁用</el-tag
                >
              </div>
              <div v-else-if="fruit == 'type'">
                <el-tag v-if="scope.row.status == 1" type="primary"
                  >积分</el-tag
                >
                <el-tag v-if="scope.row.status == 2" type="primary"
                  >提货券</el-tag
                >
                <el-tag v-if="scope.row.status == 3" type="primary"
                  >提货券比例范围</el-tag
                >
                <el-tag v-if="scope.row.status == 99" type="primary"
                  >未中奖</el-tag
                >
              </div>
              <div v-else>
                {{ scope.row[fruit] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            width="240"
            prop="address"
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="'raffle/status'"
                style="margin: 5px"
                v-if="scope.row.status == 1"
                type="warning"
                size="mini"
                @click="saveStatus(scope.row, 2)"
              >
                禁用
              </el-button>
              <el-button
                v-hasPermi="'raffle/status'"
                style="margin: 5px"
                v-if="scope.row.status == 2"
                type="success"
                size="mini"
                @click="saveStatus(scope.row, 1)"
              >
                启用
              </el-button>
              <el-button
                v-hasPermi="'raffle/edit'"
                style="margin: 5px"
                type="primary"
                size="mini"
                @click="editCoupon(scope.row)"
              >
                编辑
              </el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @confirm="deleteCoupon(scope.row)"
              >
                <el-button
                  v-hasPermi="'raffle/del'"
                  style="margin: 5px"
                  type="danger"
                  size="mini"
                  slot="reference"
                >
                  删除
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col style="text-align: right">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="searchForm.page"
          :limit.sync="searchForm.count"
          @pagination="getListWay"
        />
      </el-col>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="submitVisible"
      width="600px"
      @close="submitClose"
    >
      <el-row :gutter="20" v-loading="submitLoading">
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="110px"
          class="demo-ruleForm"
        >
          <el-col :span="22">
            <el-form-item label="模版名称" prop="template_name">
              <el-input
                placeholder="请输入模版名称"
                v-model="form.template_name"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="1">积分</el-radio>
                <el-radio :label="2">提货券</el-radio>
                <el-radio :label="3">提货券比例范围</el-radio>
                <el-radio :label="99">未中奖</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="提示语" prop="language">
              <el-input
                placeholder="请输入提示语"
                v-model="form.language"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="图片" prop="image">
              <logo-upload
                :single-file="image"
                :show-file-list="false"
                accept="image/jpeg, image/png"
                @uploadCallback="imageCallback"
              />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="submitLoading" @click="submitVisible = false"
          >取 消</el-button
        >
        <el-button :loading="submitLoading" type="primary" @click="submitWay"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
  
  <script>
import {
  SaveAwardTemplate,
  getAwardTemplateList,
  getAwardTemplateInfo,
  delAwardTemplate,
  SaveAwardTemplateStatus,
} from "@/api/activity/index";
import LogoUpload from "@/components/FileUpload";
const tableTheadOption = {
  id: {
    label: "ID",
    field: "id",
  },
  created_at: {
    label: "创建时间",
    field: "created_at",
  },
  template_name: {
    label: "模板名称",
    field: "template_name",
  },
  type: {
    label: "类型",
    field: "type",
  },
  status: {
    label: "状态",
    field: "status",
  },
  language: {
    label: "提示语",
    field: "language",
  },
};
const allTableThead = [
  "id",
  "created_at",
  "template_name",
  "type",
  "status",
  "language",
];
const defaultTableThead = [
  "id",
  "created_at",
  "template_name",
  "type",
  "status",
  "language",
];
export default {
  components: {
    LogoUpload,
  },
  watch: {
    checkboxTableThead(valArr) {
      this.tableThead = this.allTableThead.filter(
        (i) => valArr.indexOf(i) >= 0
      );
      this.tableKey = this.tableKey + 1;
    },
  },
  data() {
    return {
      // 动态显示表头默认表头
      tableTheadOptions: tableTheadOption,
      allTableThead: allTableThead,
      tableThead: defaultTableThead, // 默认表头
      checkboxTableThead: defaultTableThead, // 默认表头值
      tableKey: 1, // 为了保证table 每次都会重渲
      loading: true,
      title: "添加模版",
      searchForm: {
        template_name: "", // 抽奖活动名称
        status: "", // 状态状态：-1过期 1开启 2进行中 3关闭
        type: "",
        page: 1,
        count: 10,
      },
      dataList: [],
      total: 0,
      form: {
        id: "",
        type: 99,
        template_name: "",
        language: "",
        image: "",
      },
      image: {},
      rules: {
        template_name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^0-9a-zA-Z\u4e00-\u9fa5]/g;
              if (!value) {
                callback(new Error("请输入模版名称"));
              } else {
                if (req.test(value)) {
                  callback(new Error("模版名称中不能存在特殊字符"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        type: [
          {
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          },
        ],
        language: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^0-9a-zA-Z\u4e00-\u9fa5]/g;
              if (!value) {
                callback(new Error("请输入提示语"));
              } else {
                if (req.test(value)) {
                  callback(new Error("提示语中不能存在特殊字符"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        image: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^0-9a-zA-Z\u4e00-\u9fa5]/g;
              if (!this.form.image) {
                callback(new Error("请上传图片"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
      submitLoading: false,
      submitVisible: false,
    };
  },
  created() {
    this.getListWay();
  },
  methods: {
    getListWay() {
      this.loading = true;
      getAwardTemplateList(this.searchForm).then((res) => {
        this.loading = false;
        if (res.code !== 200 || res.status !== 1) {
          this.loading = false;
          return this.$messages.error(res.msg);
        }
        this.dataList = res.data.list;
        this.total = res.data.total;
      });
    },
    resetting() {
      this.searchForm = {
        award_name: "", // 抽奖活动名称
        status: "", // 状态状态：-1过期 1开启 2进行中 3关闭
        page: 1,
        count: 10,
      };
      this.getListWay();
    },
    deleteCoupon(row) {
      this.loading = true;
      delAwardTemplate({ id: row.id })
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.$messages.success("删除成功");
          this.getListWay();
        })
        .catch((err) => {
          this.loading = false;
          this.$messages.error(err.msg);
        });
    },
    saveWay() {
      this.submitVisible = true;
    },
    editCoupon(row) {
      this.submitVisible = true;
      this.submitLoading = true;
      getAwardTemplateInfo({ id: row.id }).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.submitLoading = false;
          this.$messages.error(res.msg);
          return;
        }
        this.form.id = res.data.id;
        this.form.template_name = res.data.template_name;
        this.form.type = res.data.type;
        this.form.language = res.data.language;
        this.form.image = res.data.image;
        this.image = {
          url: res.data.image,
        };
        this.submitLoading = false;
        console.log(res);
      });
      //   this.$router.push("/activity/raffle/save?id=" + row.id);
    },
    resetFormWay() {
      this.form = {
        id: "",
        type: "",
        template_name: "",
        language: "",
        image: "",
      };
      this.image = {};
      this.$refs.form.resetFields();
    },
    submitWay() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          SaveAwardTemplate(this.form).then((res) => {
            this.submitLoading = false;
            if (res.code !== 200 || res.status !== 1) {
              this.$messages.error(res.msg);
              return;
            }
            this.$messages.success(res.msg);
            this.resetFormWay();
            this.submitVisible = false;
            this.getListWay();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 修改状态
    saveStatus(row, num) {
      var obj = {
        id: row.id,
        status: num,
      };
      this.loading = true;
      SaveAwardTemplateStatus(obj)
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.$messages.success("操作成功");
          this.getListWay();
        })
        .catch((err) => {
          this.$messages.error(err.msg);
          this.loading = false;
        });
    },
    imageCallback(file) {
      this.image = file;
      this.form.image = file.url;
    },
    // 添加修改弹框关闭调用
    submitClose() {
      this.resetFormWay();
      this.submitVisible = false;
    },
  },
};
</script>
  
  <style>
</style>